import { baseName } from '@/const'
import {
  setToken as updateToken,
  getToken,
  setUser,
  getUser,
  removeToken,
  removeUser,
} from '@/app/storage'
import { LOGIN_ROUTER_NAME, REDIRECT_HOME_PATH } from '@/const/router'
import type { UserStore } from '@/store/interface/user'
import router from '@/router'
import useAuthStore from './auth'

export default defineStore(`${baseName}__userStore`, (): UserStore => {
  const authStore = useAuthStore()

  // const token = ref<string | null>(getToken() || null)
  const token = ref<string | null>('123')
  const userInfo = ref<any | null>(getUser() || null)

  function setToken(value: string) {
    token.value = value
    updateToken(value)
  }

  function setUserInfo(value: any) {
    userInfo.value = value
    setUser(value)
  }

  function logout() {
    token.value = null
    userInfo.value = null
    authStore.clearAuthMenuList()
    removeToken()
    removeUser()
    setTimeout(() => router.replace(`/${LOGIN_ROUTER_NAME}`), 500)
  }

  async function login(data: any) {
    data.isRemember && (await setToken(new Date().getTime().toString()))
    await setUserInfo(data)
    router.push(REDIRECT_HOME_PATH)
  }

  return {
    token,
    userInfo,
    setToken,
    setUserInfo,
    logout,
    login,
  }
})
